package org.example;

import bean.DB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/upAddressServlet")
public class upAddressServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userIdStr = (String) request.getSession().getAttribute("userId");
        String newAddress = request.getParameter("address");

        if (userIdStr == null || newAddress == null || newAddress.trim().isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID或地址不能为空");
            return;
        }

        int userId = Integer.parseInt(userIdStr);

        try (Connection conn = new DB().createConn()) {
            String updateAddressSql = "UPDATE users SET address = ? WHERE id = ?";
            try (PreparedStatement pstmt = conn.prepareStatement(updateAddressSql)) {
                pstmt.setString(1, newAddress);
                pstmt.setInt(2, userId);

                int rowsAffected = pstmt.executeUpdate();
                if (rowsAffected > 0) {
                    response.sendRedirect("userPage.jsp");  // 地址更新成功，重定向回结算页面
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新收货地址失败");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库错误");
        }
    }
}
